package com.lucence.b_thead;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Version;
import org.junit.Test;

import com.lucence.a_helloword.Article;
import com.lucence.util.ArticleDocument;
import com.lucence.util.Config;
import com.lucence.util.LuceneUtil;

public class TestIndexWriterAdnIndexSearcher {
	@Test
	public void testIndexWriterAdnIndexSearcher() throws Exception {
		{
			IndexWriter indexWriter = LuceneUtil.getIndexWriter();
			Document doc = new Document();
			Article article = new Article();
			article.setId("1");
			article.setTitle("Lucene is a sousou");
			article.setContent("Lucene is apache");
			indexWriter.addDocument(ArticleDocument.articleToDocument(article));
		}
		{
			IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher();
			String queryString = "Lucene";
			QueryParser queryParser = new MultiFieldQueryParser(
					Version.LUCENE_36, new String[] { "title", "content" },
					Config.getAnalyzer());
			Query query = queryParser.parse(queryString);
			TopDocs topDocs = indexSearcher.search(query, 100);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			if (scoreDocs != null && scoreDocs.length > 0) {
				System.out.println("数据数量："+scoreDocs.length);
				for (int i = 0; i < scoreDocs.length; i++) {
					ScoreDoc scoreDoc = scoreDocs[i];
					System.out.println("得分:" + scoreDoc.score);
					int doc = scoreDoc.doc;
					Document document = indexSearcher.doc(doc);
					Article article = ArticleDocument
							.articleToDocument(document);
					System.out.println("--------------------");
					System.out.println(article.getId());
					System.out.println(article.getTitle());
					System.out.println(article.getContent());
				}
			}
		}
	}
}
